package tech.yunqian.slim.project.domain;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import tech.yunqian.slim.project.enums.TriggerLogic;

@Slf4j
@Data
public class MonitorRuleTrackingItem {
    private MonitorRule monitorRule;
    private Alarm alarm;
    private Map<Integer, MonitorConditionTrackingItem> monitorConditionTrackingItemMap;

    public MonitorRuleTrackingItem(MonitorRule monitorRule) {
        this.monitorRule = monitorRule;
        this.alarm = null;
        this.monitorConditionTrackingItemMap = new HashMap<>();
    }

    public Set<Integer> ids() {
        return monitorConditionTrackingItemMap.keySet();
    }

    public Boolean contains(Integer monitorConditionId) {
        return this.monitorConditionTrackingItemMap.containsKey(monitorConditionId);
    }

    public MonitorConditionTrackingItem getItem(Integer monitorConditionId) {
        return this.monitorConditionTrackingItemMap.get(monitorConditionId);
    }

    public void putItem(Integer monitorConditionId, MonitorConditionTrackingItem monitorConditionTrackingItem) {
        this.monitorConditionTrackingItemMap.put(monitorConditionId, monitorConditionTrackingItem);
    }

    public void removeItem(Integer monitorConditionId) {
        this.monitorConditionTrackingItemMap.remove(monitorConditionId);
    }

    public Boolean isFulfilled() {
        TriggerLogic triggerLogic = TriggerLogic.valueOfCode(monitorRule.getTriggerLogic());
        Integer fulfilledConditionCount = 0;
        for (Map.Entry<Integer, MonitorConditionTrackingItem> entry : monitorConditionTrackingItemMap.entrySet()) {
            if (entry.getValue().isFulfilled()) {
                fulfilledConditionCount++;
            }
        }
        if (triggerLogic.equals(TriggerLogic.AND)) {
            return fulfilledConditionCount.equals(monitorRule.getConditionCount());
        }
        return fulfilledConditionCount > 0;
    }
}